<?php

namespace App\Tasks;

use App\Clients\Lakala\AccountAuthUserInfo;
use App\Clients\Lakala\MerTransQueryTranInfoSum;
use App\Clients\Lakala\MerTransSepQuerySeps;
use App\Clients\Yisheng\TermStlmTotal;
use App\Clients\Yisheng\TradeGetTotal;
use App\Models\MallDateFinance;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;

class LakalaSyncDatasTask extends MeiTuanMallTask
{

    public function handleQeqData($postData){
        $requestTime = date("YmdHis");
        $requestId = $requestTime.rand(1000000,9999999);
        $postData["requestId"] = $requestId;
        $postData["requestTime"] = $requestTime;
        $postData["reqTime"] = $requestTime;
        $postData["systemCode"] = "MERDASH";
        $postData["version"] = "1.0";
        return $postData;
    }

    /**
     * @throws GuzzleException
     */
    protected function changeIdentityAndMer(){
        $service = new AccountAuthUserInfo($this->account);
        $queryData = [
            "isGuest"=>true
        ];
        $service->loopExecute($queryData)->contents();


        $postData = ["isGuest"=>true];
        $postData = $this->handleQeqData($postData);
        $cookies = json_decode($this->account->account->cookies,true);
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
            "AUTHORIZATION"=>$cookies["authorization"],
        ];
        $cookieJar = new CookieJar();
        $client = new Client([
            "verify"=>false,
            "http_errors"=>false,
            'cookies' => $cookieJar,
        ]);
        $url = "https://m2.lakala.com/m/a/lams/merdash/queryAllMerList";
        $content = $client->post($url,["json"=>$postData,"headers"=>$headers])->getBody()->getContents();
        $content = json_decode($content,true);
        $content = $content["data"];
        $roleData = [];
        foreach ($content as $cont){
            if($cont["merchantNo"] == $this->mall->merchant_no){
                $roleData = $cont;
                break;
            }
        }
        $postData = [
            "method"=>"userIdentity.set",
            "lamsRoleId"=>$roleData["roleId"],
            "merDataSources"=>$roleData["merFrom"],
            "authUserId"=>"",
            "defaultMerInnerNo"=>$roleData["merInnerNo"],
            "defaultMerchantNo"=>$roleData["merchantNo"],
        ];
        $postData = $this->handleQeqData($postData);
        $url = "https://m2.lakala.com/m/a/mp3Ms/userIdentity/changeIdentityAndMer";
        $content = $client->post($url,["json"=>$postData,"headers"=>$headers])->getBody()->getContents();
        $cookiesV = $cookieJar->toArray();
        $cookieStr = [];
        foreach ($cookiesV as $cookie){
            $cookieStr[] = $cookie["Name"]."=".$cookie["Value"];
        }
        $cookieStr = implode("; ",$cookieStr);
        $cookies["cookies"] = $cookieStr;
        return $cookies;

    }

    /**
     * @throws GuzzleException
     */
    public function execute(): void
    {

        $cookies = $this->changeIdentityAndMer();
//        var_dump($cookies);
//        exit();
        $startDate = $this->maxDate(3);
        $diffDate = (strtotime(date("Y-m-d",time())) - strtotime(date("Y-m-d",strtotime($startDate)))) / 86400;
        $queryDates = [];
        foreach (range(0,$diffDate,1) as $index=>$item){
            $beginDate = date("Ymd",strtotime($startDate) + 1 * $index * 86400);
            $sdate = date("Y-m-d",strtotime($startDate) + 1 * $index * 86400);
            $queryDates[] = [
                "s"=>$sdate,
                "income"=>[
                    "endDate"=>$beginDate,
                    "endTime"=>"235959",
                    "merchantNos"=>$this->mall->merchant_no,
                    "merchantNo"=>$this->mall->merchant_no,
                    "openEntity"=>$this->mall->merchant_no,
                    "startDate"=>$beginDate,
                    "startTime"=>"000000",
                    "groupType"=>"tranDate",
                    "page"=>1,
                    "size"=>10,
                ],
                "sub"=>[
                    "end_date"=>$beginDate,
                    "merchant_no"=>$this->mall->merchant_no,
                    "openEntity"=>$this->mall->merchant_no,
                    "outOrgCode"=>"000000",
                    "recv_no"=>$this->mall->poi_id,
                    "start_date"=>$beginDate,
                ]
            ];
        }
        $incomeClient = new MerTransQueryTranInfoSum($this->account);
        $incomeClient->setCookieJar($cookies);
        $subClient = new MerTransSepQuerySeps($this->account);
        $subClient->setCookieJar($cookies);
        foreach ($queryDates as $queryDate){
            $udate = $queryDate["s"];
            var_dump($udate);
            $model = MallDateFinance::query()
                ->where("merchant_no",$this->mall->merchant_no)
                ->where("date",$udate)
                ->first();
            if(!empty($model) && $model->is_update == 1){
                continue;
            }
            $response = $incomeClient->loopExecute($queryDate["income"])->contents();
            $income = empty($response["settleAmt"]) ? 0 : $response["settleAmt"];
            $subaoumt = 0;
            $subQuery = $queryDate["sub"];
            $page = 1;
            $pageSize = 100;
            $subQuery["pageNum"] = $page;
            $subQuery["pageSize"] = $pageSize;
            $subQuery["page_no"] = $page;
            $subQuery["page_size"] = $pageSize;
            $response = $subClient->loopExecute($subQuery)->contents();
            $total = $response["total"];
            $pageItems = $response["pageItems"];
            foreach ($pageItems as $pageItem){
                $subaoumt += $pageItem["amt"];
            }
            $totalPage = ceil($total / $pageSize);
            if($totalPage >= 2){
                for($i=2;$i<=$totalPage;$i++){
                    $subQuery["pageNum"] = $i;
                    $subQuery["page_no"] = $i;
                    $response = $subClient->loopExecute($subQuery)->contents();
                    $total = $response["total"];
                    $pageItems = $response["pageItems"];
                    foreach ($pageItems as $pageItem){
                        $subaoumt += $pageItem["amt"];
                    }
                }
            }
            $subaoumt = round($subaoumt,2);
            empty($model) and $model = new MallDateFinance;
            $model->bill_no = $udate;
            $model->merchant_no = $this->mall->merchant_no;
            $model->date = $udate;
            $model->income = $income;
            $model->settle_money = $subaoumt;
            $model->save();

        }

    }
}
